import { game, native, sys } from "cc";
import { EventName } from "../manager/EventMgr";
import { EventMgr } from "../manager/EventMgr";
import { ReportDataAdView } from "../net/EventReport";
import LocalValues from "../data/LocalValues";


export default class NativeHelper {

    private static _adjustAdid = '';
    public static get adjustAdid() {
        if (!this._adjustAdid) {
            this._adjustAdid = LocalValues.getString('adjustAdid') || '';
        }
        return this._adjustAdid;
    }
    private static _deviceId = '';
    public static get deviceId() {
        return this._deviceId;
    }
    private static _systemInfo:ISystemInfo;
    public static get systemInfo() {
        if (!this._systemInfo) {
            const json = LocalValues.getString('systemInfo');
            if (json) {
                this._systemInfo = JSON.parse(json) as ISystemInfo;
            }
        }
        return this._systemInfo;
    }
    private static _firebaseToken = '';
    public static get firebaseToken() {
        return this._firebaseToken;
    }
    private static _netState = false;
    public static get netState() {
        if (sys.isBrowser) {
            return true;
        }
        return this._netState;
    }
    public static launchTime = '';
    private static _product: IProduct = null;
    public static get product() {
        if (!this._product) {
            this._product = LocalValues.getObject('payProduct') as IProduct;
        }
        return this._product;
    }

    public static readonly isNative: boolean = sys.isNative;
    public static readonly isIOS: boolean = sys.Platform.IOS === sys.platform;
    public static readonly isAndroid: boolean = sys.Platform.ANDROID === sys.platform;

    public static get isCanHotUpdate(): boolean {
        return this.isAndroid; // 暂时只支持安卓
    }

    public static init() {
        console.log('NativeHelper.init');
        this.emit('init');
        this.on(NativeEvent.respAdjustAdid, this.onAdjustAdid);
        this.on(NativeEvent.respDeviceId, this.onDeviceId);
        this.on(NativeEvent.respSystemInfo, this.onSystemInfo);
        this.on(NativeEvent.respFirebaseToken, this.onFirebaseToken);
        this.on(NativeEvent.respNetState, this.onNetState);
        this.on(NativeEvent.respAdLoadInter, this.onAdLoadInter);
        this.on(NativeEvent.respAdLoadRewarded, this.onAdLoadRewarded);
        this.on(NativeEvent.respAdLoadFaildInter, this.onAdLoadFaildInter);
        this.on(NativeEvent.respAdLoadFaildRewarded, this.onAdLoadFaildRewarded);
        this.on(NativeEvent.respShowAdInter, this.onShowAdInter);
        this.on(NativeEvent.respShowAdRewarded, this.onShowAdRewarded);
        this.on(NativeEvent.respAdRewarded, this.onAdRewarded);
        this.on(NativeEvent.respAdTypeChange, this.onAdTypeChange);
        this.on(NativeEvent.respPaySuccess, this.onPaySuccess);
        this.on(NativeEvent.respPayFail, this.onPayFail);
        this.on(NativeEvent.respNotificationAuthority, this.onNotificationAuthority);
        if (!this.isNative) {
            this._adjustAdid = 'testAdjustAdid';
            this._deviceId = 'testDeviceId';
        }
    }

    public static restart() {
        if (this.isNative) {
            game.restart();
        } else {
            location.reload();
        }
    }

    public static emit(event: string, arg?: string) {
        if (NativeHelper.isNative) {
            native.jsbBridgeWrapper.dispatchEventToNative(event,arg);
        }
    }

    public static on(event: string, callback: (arg: string) => void) {
        if (NativeHelper.isNative) {
            native.jsbBridgeWrapper.addNativeEventListener(event, callback.bind(this))
        }
    }
    //=================请求=================
    public static callVibrate(ms: number, strength: number) {
        if (NativeHelper.isAndroid) {
            this.emit(NativeEvent.callVibrate, ms+'');
        } else if (NativeHelper.isIOS) {
            this.emit(NativeEvent.callVibrate, ms+''); // ios还不确定能不能支持强度
        }
    }
    public static callSaveImageToGallery(filePath: string) {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callSaveImageToGallery, filePath);
        }
    }
    public static callMailTo(email: string, subject: string, text = '') {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callMailTo, JSON.stringify({email, subject, text}));
        }
    }
    public static callOpenUrl(url: string) {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callOpenUrl, url);
        }
    }
    public static callCopyText(text: string) {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callCopyText, text);
        } else if (sys.isBrowser) {
            // 浏览器复制
            const input = document.createElement('input');
            input.value = text;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
        }
    }
    public static callAdLoad(type: 'interstitial' | 'rewarded' | 'banner') {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callAdLoad, type);
        }
    }
    public static callAdUserId(uid: string) {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callAdUserId, uid);
        }
    }
    public static callShowAdInter(data: ReportDataAdView) {
        // console.log('NativeHelper.callShowAdInter', data.adpos, data.customData);
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callShowAdInter, JSON.stringify(data.placement)
                + '||' + JSON.stringify(data.customData)
                + '||' + (data.changeAdType ? '1' : '0'));
        }
    }
    public static callShowAdRewarded(data: ReportDataAdView) {
        // console.log('NativeHelper.callShowAdRewarded', data.placement, data.customData);
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callShowAdRewarded, JSON.stringify(data.placement)
                + '||' + JSON.stringify(data.customData)
                + '||' + (data.changeAdType ? '1' : '0'));
        } else {
            this.onAdRewarded('1');
        }
    }
    /**
     * 显示banner广告
     * @param bShow 是否显示
     * @param data bShow为true时，data为banner数据，否则为null
     */
    public static callAdBanner(bShow: boolean, data?: ReportDataAdView) {
        if (NativeHelper.isNative) {
            let str = '';
            if (bShow) {
                str = JSON.stringify(data.placement) + '||' + JSON.stringify(data.customData)
            }
            this.emit(NativeEvent.callAdBanner, str);
        }
    }
    public static callPayResume() {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callPayResume);
        }
    }
    public static callPayBuy(product: IProduct) {
        this._product = product;
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callPayBuy, product.productId);
        } else {
            const str = '{"token":"hnbalhbehmdfnelcanolcfbl.AO-J1OxYpTTK0lThffC7cHpGaPhNghyHTRxYchRTlYCyOjfq6vOwal0a71o5vZZP-F-NJdg1pqbaOOHAHkIa2H7yLJsCwqbAigTUyVXsGL0lTQH_3R7kT6szN720P5ecMhfyIxP-H7BZ","transactionId":"GPA.3381-0047-0270-05568"}';
            EventMgr.emit(EventName.onPaySuccess, JSON.parse(str), product);
        }
    }
    public static callPayConsume(token: string) {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callPayConsume, token);
        }
    }
    /**
     * 调用评价
     */
    public static callReview() {
        if (NativeHelper.isNative) {
            this.emit(NativeEvent.callReview);
        }
    }
    //=====================================
    //=================回调=================
    private static onAdjustAdid(adjustAdid: string) {
        console.log("onAdjustAdid", adjustAdid)
        NativeHelper._adjustAdid = adjustAdid||'';
        EventMgr.emit(EventName.onAdjustAdid, adjustAdid);
        LocalValues.setString('adjustAdid', adjustAdid);
    }

    private static onDeviceId(deviceId: string) {
        console.log("onDeviceId", deviceId)
        NativeHelper._deviceId = deviceId||'';
    }

    private static onSystemInfo(systemInfo: string) {
        console.log("onSystemInfo", systemInfo)
        NativeHelper._systemInfo = JSON.parse(systemInfo) as ISystemInfo;
        LocalValues.setString('systemInfo', systemInfo);
    }

    private static onFirebaseToken(firebaseToken: string) {
        console.log("onFirebaseToken", firebaseToken)
        NativeHelper._firebaseToken = firebaseToken||'';
    }
    private static onNetState(netState: string) {
        console.log("onNetState", netState)
            NativeHelper._netState = netState == '1';
    }
    private static onAdLoadInter(json: string) {
        console.log("xxxjs onAdLoadInter", json)
        EventMgr.emit(EventName.onAdLoadInter, true, json);
    }
    private static onAdLoadFaildInter(err: string) {
        console.log("xxxjs onAdLoadFaildInter", err)
        EventMgr.emit(EventName.onAdLoadInter, false, err);
    }
    private static onAdLoadRewarded(json: string) {
        console.log("xxxjs onAdLoadRewarded", json)
        EventMgr.emit(EventName.onAdLoadRewarded, true, json);
    }
    private static onAdLoadFaildRewarded(err: string) {
        console.log("xxxjs onAdLoadFaildRewarded", err)
        EventMgr.emit(EventName.onAdLoadRewarded, false, err);
    }
    private static onShowAdInter(bSuccess: string) {
        console.log("xxxjs onShowAdInter", bSuccess)
        EventMgr.emit(EventName.onShowAdInter, bSuccess == '1');
        if (NativeHelper._adRewardedCallback) {
            NativeHelper._adRewardedCallback(bSuccess == '1');
            NativeHelper._adRewardedCallback = null;
        }
    }
    private static onShowAdRewarded(bSuccess: string) {
        console.log("xxxjs onShowAdRewarded", bSuccess)
        EventMgr.emit(EventName.onShowAdRewarded, bSuccess == '1');
    }
    private static onAdRewarded(bSuccess: string) {
        console.log("xxxjs onAdRewarded", bSuccess)
        if (NativeHelper._adRewardedCallback) {
            NativeHelper._adRewardedCallback(bSuccess == '1');
            NativeHelper._adRewardedCallback = null;
        }
    }
    private static onAdTypeChange(json: string) {
        EventMgr.emit('onAdTypeChange', json);
    }
    private static _adRewardedCallback: (bSuccess: boolean) => void = null;
    public static onceAdRewardedCallback(callback: (bSuccess: boolean) => void) {
        NativeHelper._adRewardedCallback = callback;
    }
    private static onPaySuccess(json: string) {
        console.log("xxxjs onPaySuccess", json)
        const data = JSON.parse(json) as {transactionId: string, token: string};
        EventMgr.emit(EventName.onPaySuccess, data, NativeHelper.product);
        LocalValues.setObject('payProduct', this._product);
    }
    private static onPayFail(code: string) {
        console.log("xxxjs onPayFail", code)
        EventMgr.emit(EventName.onPayFail, code, NativeHelper.product);
    }
    private static onNotificationAuthority(result: 'reject' | 'allow' | 'runtimeAllow') {
        console.log("xxxjs onNotificationAuthority", result)
        EventMgr.emit('onNotificationAuthority', result);
    }
    //=====================================
}

export enum NativeEvent {
    respAdjustAdid = "respAdjustAdid",
    respDeviceId = "respDeviceId",
    respSystemInfo = "respSystemInfo",
    respFirebaseToken = "respFirebaseToken",
    respNetState = "respNetState",
    respAdLoadInter = "respAdLoadInter", // 插屏广告加载成功
    respAdLoadRewarded = "respAdLoadRewarded", // 激励广告加载成功
    respAdLoadFaildInter = "respAdLoadFaildInter", // 插屏广告加载失败
    respAdLoadFaildRewarded = "respAdLoadFaildRewarded", // 激励广告加载失败
    respShowAdInter = "respShowAdInter", // 插屏广告是否成功播放
    respShowAdRewarded = "respShowAdRewarded", // 激励广告是否成功播放
    respAdRewarded = "respAdRewarded", // 激励广告发放奖励
    respAdTypeChange = "respAdTypeChange", // 广告类型切换
    respPaySuccess = "respPaySuccess", // 支付成功
    respPayFail = "respPayFail", // 支付失败
    respNotificationAuthority = "respNotificationAuthority", // 通知权限获取
    callVibrate = "callVibrate",
    callSaveImageToGallery = "callSaveImageToGallery",
    callMailTo = "callMailTo",
    callOpenUrl = "callOpenUrl",
    callCopyText = "callCopyText",
    callAdLoad = "callAdLoad",
    callAdUserId = "callAdUserId",
    callShowAdInter = "callShowAdInter",
    callShowAdRewarded = "callShowAdRewarded",
    callAdBanner = "callAdBanner",
    callPayResume = "callPayResume", // 启动时订单补漏
    callPayBuy = "callPayBuy",
    callPayConsume = "callPayConsume", // 消耗订单
    callTDLogin = "callTDLogin",
    callTDTrack = "callTDTrack",
    callTDUserSet = "callTDUserSet",
    callReview = "callReview",
}

export interface ISystemInfo {
    cpuInfo: string;
    gpuInfo: string;
    ramInfo: {
        occupied: number;
        total: number;
    }
    romInfo: {
        occupied: number;
        total: number;
    }
    network: string;
    conversationData: string;
    systemInfo: string;
    idfa: string;
    model: string; // 设备型号
    systemVersion: string; // 系统版本
    apiLevel: number; // 安卓API等级
}

export interface IProduct {
    productId: string;
    price: number;
    name: string;
}
